package org.tungse.controller;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.RandomUtil;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @Author : Tungse
 * @Date: 2025/7/3 16:38
 * @Description:
 */
@RestController
@RequestMapping("/arthas")
public class ArthasTestController {


    final Object r1 = new Object();
    final Object r2 = new Object();
    List<byte[]> array = new ArrayList<>();
    @RequestMapping("/oom/test1/{count}")
    public String oom1Test(@PathVariable int count) {
        byte[] bytes = new byte[count * 1024 * 1024];
        array.add(bytes);
        return "测试";
    }

    @RequestMapping("/oom/test/{count}")
    public String oomTest(@PathVariable int count) {
        System.out.println("count: " + count);
        String[] arrStrs = new String[count];
        for (int i = 0; i < count; i++) {
            arrStrs[i] = RandomUtil.randomString(1000);
        }
        return ArrayUtil.join(arrStrs, ",");
    }

    @RequestMapping("/deadlock/test")
    public void deadlockTest() {

        System.out.println("开始死锁测试");
        new Thread(() -> {
            synchronized (r2) {
                try {
                    System.out.println("子线程睡眠1秒");
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (r1) {
                    System.out.println("线程1执行完成");
                }
            }
        }).start();

        synchronized (r1) {
            try {
                System.out.println("主线程睡眠4秒");
                Thread.sleep(4000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            synchronized (r2) {
                System.out.println("线程1执行完成");
            }
        }

    }

    @RequestMapping("/cupHigh/test/{runNumber}")
    public void cupHigh(@PathVariable Integer runNumber) {
        Integer idx = 0;
        while (!Objects.equals(runNumber, idx)) {
            idx++;
            System.out.println("cupHigh");
        }

    }

    @RequestMapping("/new/object/{runNumber}")
    public void newObject(@PathVariable Integer runNumber) {
        Integer idx = 0;
        while (!Objects.equals(runNumber, idx)) {
            idx++;
            System.out.println("cupHigh");
        }

    }
}
